import javax.imageio.ImageIO;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author Liziguo
 * @date 2022/7/15 14:11
 */
public class ImageMerge {

    public static final String INPUT_PATH = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath() + "\\image_merge";

    public static final String OUTPUT_PATH = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath() + "\\image_merge.png";

    public static void main(String[] args) {
        File file = new File(INPUT_PATH);
        if (!file.exists()) {
            throw new RuntimeException("路径不存在 " + file.getAbsolutePath());
        }
        if (!file.isDirectory()) {
            throw new RuntimeException("请选择目录 " + file.getAbsolutePath());
        }
        File[] files = file.listFiles();
        if (files == null || files.length == 0) {
            throw new RuntimeException("该目录为空 " + file.getAbsolutePath());
        }
        List<File> fileList = Arrays.stream(files).toList();

        System.out.println("合成顺序为:");
        for (File subFile : fileList) {
            System.out.println(subFile.getName());
        }
        System.out.println("请检查图片顺序是否正确 (注:此处排序并非跟您windows资源管理器的排序规则一致)");
        System.out.println();

        System.out.println("加载图片...");
        BufferedImage[] images = new BufferedImage[files.length];
        for (int i = 0, len = fileList.size(); i < len; i++) {
            File subFile = fileList.get(i);
            try {
                images[i] = ImageIO.read(subFile);
            } catch (IOException e) {
                throw new RuntimeException("图片:" + subFile.getAbsolutePath() + " 加载失败");
            }
        }

        System.out.println("检查图片大小是否一致...");
        final BufferedImage first = images[0];
        final int width = first.getWidth();
        final int height = first.getHeight();
        for (int i = 1, len = images.length; i < len; i++) {
            if (width != images[i].getWidth() || height != images[i].getHeight()) {
                throw new RuntimeException("所有图片大小必须一致");
            }
        }

        System.out.println("生成图片...");
        final int imageType = BufferedImage.TYPE_4BYTE_ABGR_PRE;
        BufferedImage merge = new BufferedImage(width * images.length, height, imageType);
        Graphics graphics = merge.getGraphics();
        for (int i = 0, len = images.length; i < len; i++) {
            graphics.drawImage(images[i], i * width, 0, width, height, null);
        }

        System.out.println("输出图片...");
        File outputFile = new File(OUTPUT_PATH);
        try {
            ImageIO.write(merge, "png", outputFile);
        } catch (IOException e) {
            System.err.println("输出图片出现异常");
            throw new RuntimeException(e);
        }
        System.out.println("图片输出成功:\n" + outputFile.getAbsolutePath());
    }
}
